import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/helpers/safe_value_notifier.dart';
import 'package:xws/models/goods/goods_obj.dart';
import 'package:xws/res/icons.dart';
import 'package:xws/state/user_state.dart';
import 'package:xws/ui/notify/chat/start_chat.dart';
import 'package:xws/ui/others/others_page.dart';
import 'package:xws/ui/others/report_page.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/data_util.dart';
import 'package:xws/utils/dio_utils/request/goods_req.dart';
import 'package:xws/utils/dio_utils/request/user_req.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/utils/tools_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/app_img.dart';
import 'package:xws/widgets/app_label.dart';
import 'package:xws/widgets/app_list_tile.dart';
import 'package:xws/widgets/ex_value_builder.dart';
import 'package:xws/widgets/safe_scaffold.dart';
import 'package:xws/widgets/sticky_delegate.dart';

import 'comment_box.dart';
import 'play_record.dart';
import 'play_video.dart';

/// 物品详情页
class DetailPage extends StatefulWidget {
  const DetailPage({
    Key? key,
    required this.index,
    required this.goods,
    this.autoOpenComment = false,
    this.refresh,
    this.fromUser = false,
  }) : super(key: key);

  @override
  _DetailPageState createState() => _DetailPageState();

  final int index;
  final GoodsObj goods;
  final bool autoOpenComment;
  final bool fromUser;

  final Function()? refresh;
}

class _DetailPageState extends State<DetailPage> with SafeState<DetailPage> {
  late SafeValueNotifier<bool> _follow;

  GoodsObj get _g => widget.goods;

  bool get _isMe => us.info.id == _g.user.id;

  @override
  void initState() {
    super.initState();
    _follow = SafeValueNotifier<bool>(_g.user.friendFlag);
  }

  @override
  Future<void> contextReady() {
    _refreshGoods().then((_) {
      if (widget.autoOpenComment) {
        delayed(const Duration(milliseconds: 500)).then((_) {
          _comment();
        });
      }
    });
    return super.contextReady();
  }

  @override
  void dispose() {
    _follow.dispose();
    super.dispose();
  }

  /// 刷新物品
  Future<void> _refreshGoods() async {
    loading(context);

    final List<GoodsObj> gList = await getGoodsList(goodsIdList: <String>[_g.id]);
    if (gList.isNotEmpty) {
      if (!gList.single.sameWith(_g)) {
        safeSetState(() => _g.updateAll(gList.single));
        widget.refresh?.call();
      }
    }

    close(context);
  }

  /// 点击关注按钮
  Future<void> _tapFollow() async {
    if (!checkUserLogin) return;

    loading(context);

    if (_follow.value) {
      final bool r = await delFriend(_g.user.id);
      if (r) {
        _follow.value = false;
        _g.user.friendFlag = false;
      }
    } else {
      final bool r = await addFriend(_g.user.id);
      if (r) {
        _follow.value = true;
        _g.user.friendFlag = true;
      }
    }

    close(context);
  }

  /// 点赞动作
  Future<void> _likeAction() async {
    if (!checkUserLogin) return;

    if (_g.status == GoodsStatus.DELIVERED) {
      ct('物品已送出');
      return;
    }

    _g.likeFlag ? _g.likeCount-- : _g.likeCount++;
    _g.likeFlag = !_g.likeFlag;

    safeSetState(() {});

    widget.refresh?.call();

    likeGoods(_g.id);
  }

  /// 评论动作
  Future<void> _comment() async {
    if (!checkUserLogin) return;

    await push(
      context,
      CommentBox(goodsObj: _g, refresh: widget.refresh),
      routeType: RouteType.slideUp,
    );
  }

  /// 收藏动作
  Future<void> _starAction() async {
    if (!checkUserLogin) return;

    if (_g.status == GoodsStatus.DELIVERED) {
      ct('物品已送出');
      return;
    }

    _g.favoriteFlag ? _g.favoriteCount-- : _g.favoriteCount++;
    _g.favoriteFlag = !_g.favoriteFlag;

    safeSetState(() {});

    widget.refresh?.call();

    collectGoods(_g.id, !_g.favoriteFlag);
  }

  /// 点击用户
  Future<void> _onTap() async {
    if (_isMe) return;

    await push(context, OthersPage(user: _g.user, tapFollow: _tapFollow));

    _refreshGoods();
  }

  /// 想要
  Future<void> _wantGet() async {
    if (!checkUserLogin) return;

    await startChat(context, _g);
    _refreshGoods();
  }

  /// 更多操作
  Future<void> _more() async {
    final int? r = await showOptions<int>(
      context,
      options: const <String>['分享', '举报'],
    );
    if (r == null) return;

    if (checkUserLogin) {
      if (r == 0) shareGoods(_g);
      if (r == 1) push(context, ReportPage(reportType: ReportType.GOODS, id: _g.id));
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeScaffold(
      titleText: '物品详情',
      resizeToAvoidBottomInset: false,
      actions: <Widget>[
        AppBtn.center(
          onTap: _more,
          width: 36,
          height: 36,
          padding: EdgeInsets.zero,
          child: Icon(Icons.more_vert, size: 24, color: black(context)),
          color: Colors.transparent,
        ),
      ],
      body: CustomScrollView(slivers: <Widget>[
        if (!widget.fromUser) _userBox,
        _desBox,
      ]),
      bottomNavigationBar: _actionBar,
    );
  }

  /// 用户模块
  Widget get _userBox {
    return SliverPersistentHeader(
      floating: true,
      delegate: StickyDelegate(
        maxHeight: 50,
        child: AppListTile(
          onTap: _onTap,
          padding: const EdgeInsets.symmetric(horizontal: 24).copyWith(bottom: 10),
          backgroundColor: white(context),
          leading: Padding(
            padding: const EdgeInsets.only(right: 10),
            child: AppImg.fitCover(
              url: _g.user.avatarUrl,
              width: 40,
              height: 40,
              radius: 20,
            ),
          ),
          title: Text(
            _g.user.nickName,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 13,
              color: black(context).withOpacity(0.6),
              fontWeight: FontWeight.bold,
            ),
          ),
          subtitle: Text(
            getDurationDate(_g.createdAt) + ' | 发布于' + _g.reg,
            maxLines: 1,
            style: TextStyle(
              fontSize: 11,
              color: black(context).withOpacity(0.6),
            ),
          ),
          trailing: _isMe
              ? null
              : ExValueBuilder<bool>(
                  valueListenable: _follow,
                  builder: (_, bool f, ___) {
                    return AppBtn(
                      onTap: _tapFollow,
                      height: 28,
                      radius: 14,
                      padding: const EdgeInsets.symmetric(horizontal: 12),
                      color: f ? theme(context) : white(context),
                      border: Border.all(color: black(context).withOpacity(f ? 0 : 0.5), width: 0.5),
                      child: Row(
                        children: <Widget>[
                          Icon(
                            f ? Icons.check_rounded : Icons.add_rounded,
                            size: 15,
                            color: f ? white(context) : black(context),
                          ),
                          const SizedBox(width: 2),
                          Text(
                            f ? '已关注' : '关注',
                            maxLines: 1,
                            style: TextStyle(
                              fontSize: 11,
                              color: f ? white(context) : black(context),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
        ),
      ),
    );
  }

  /// 详情
  Widget get _desBox {
    return SliverPadding(
      padding: const EdgeInsets.only(top: 10),
      sliver: SliverList(
        delegate: SliverChildListDelegate(
          <Widget>[
            Container(
              color: white(context),
              padding: const EdgeInsets.all(20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  RichText(
                    text: TextSpan(
                      style: TextStyle(
                        color: black(context).withOpacity(0.8),
                        height: 2,
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        letterSpacing: 0.6,
                      ),
                      children: <InlineSpan>[
                        WidgetSpan(
                          child: AppLabel(
                            content: getQualityValue(_g.age),
                            fontSize: 12,
                            padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 6),
                            margin: const EdgeInsets.only(right: 4),
                            alignment: null,
                          ),
                        ),
                        WidgetSpan(
                          child: AppLabel(
                            content: '数量 : ${_g.count}',
                            fontSize: 12,
                            padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 6),
                            margin: const EdgeInsets.only(right: 4),
                            color: theme2(context),
                            alignment: null,
                          ),
                        ),
                        WidgetSpan(
                          child: AppLabel(
                            content: _g.distance,
                            fontSize: 12,
                            padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 6),
                            margin: const EdgeInsets.only(right: 4),
                            color: theme2(context),
                            alignment: null,
                          ),
                        ),
                        WidgetSpan(
                          child: AppLabel(
                            content: '免费',
                            fontSize: 12,
                            padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 6),
                            margin: const EdgeInsets.only(right: 10),
                            color: Colors.green[600],
                            alignment: null,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 10),
                  Text(
                    _g.description,
                    style: TextStyle(
                      color: black(context).withOpacity(0.8),
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      letterSpacing: 0.6,
                    ),
                  ),
                  const SizedBox(height: 20),
                  if (_g.recordUrl.isNotEmpty) PlayRecord(url: _g.recordUrl),
                  if (_g.recordUrl.isNotEmpty) const SizedBox(height: 20),
                  if (_g.videoUrl.isNotEmpty)
                    PlayVideo(
                      path: _g.videoUrl,
                      cover: _g.photoUrlList.first,
                      width: sw - 40,
                    ),
                  if (_g.videoUrl.isNotEmpty) const SizedBox(height: 20),
                  _buildImgs,
                  if (_g.originalPrice > 0) const Divider(height: 20),
                  if (_g.originalPrice > 0) _price,
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 原价
  Widget get _price {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Text(
          '入手价',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.bold,
            color: disable(context),
          ),
        ),
        Text(
          '${_g.originalPrice}',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: disable(context),
          ),
        ),
      ],
    );
  }

  /// 图片
  Widget get _buildImgs {
    final List<String> imgs = _g.photoUrlList;

    final double w = sw - 40;
    final double halfW = w / 2 - 1;

    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Wrap(
        spacing: 2,
        runSpacing: 2,
        children: List<Widget>.generate(
          imgs.length,
          (int i) {
            bool f = true;
            if (imgs.length > 4) {
              f = imgs.length - i > 4;
            }

            final String tag = homeHeroTag.replaceFirst('{item}', widget.index.toString());

            return GestureDetector(
              onTap: () async => await assetsViewer(
                context,
                imgs,
                initIndex: i,
                heroTag: tag,
              ),
              child: ConstrainedBox(
                constraints: const BoxConstraints(maxHeight: 1000),
                child: AppImg(
                  heroTag: tag + i.toString(),
                  alignment: Alignment.topCenter,
                  url: imgs[i],
                  width: f ? w : halfW,
                  height: f ? null : halfW,
                  fit: f ? BoxFit.contain : BoxFit.cover,
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  /// 底部操作栏
  Widget get _actionBar {
    return Container(
      height: 66,
      padding: const EdgeInsets.symmetric(horizontal: 20),
      alignment: Alignment.center,
      child: Row(
        children: <Widget>[
          _buildActionItem(IR.un_like, IR.like, '赞一个', _g.likeFlag, onTap: _likeAction),
          const SizedBox(width: 10),
          _buildActionItem(IR.comment, IR.comment, '留言', false, onTap: _comment),
          const SizedBox(width: 10),
          _buildActionItem(IR.un_star, IR.star, '收藏', _g.favoriteFlag, onTap: _starAction),
          const Spacer(),
          _buildTr,
        ],
      ),
      decoration: BoxDecoration(
        color: white(context),
        boxShadow: <BoxShadow>[
          BoxShadow(
            blurRadius: 10,
            color: Colors.black.withOpacity(0.1),
          ),
        ],
      ),
    );
  }

  /// 构建尾部
  Widget get _buildTr {
    if (_g.status == GoodsStatus.DELIVERED) {
      return Text(
        '已送出',
        style: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          color: disable(context),
        ),
      );
    } else if (!_isMe) {
      return AppBtn(
        onTap: _wantGet,
        height: 36,
        radius: 6,
        alignment: Alignment.center,
        text: '我想要',
        padding: const EdgeInsets.symmetric(horizontal: 20),
        textStyle: TextStyle(
          color: white(context),
          fontSize: 14,
          fontWeight: FontWeight.bold,
        ),
      );
    }

    return const SizedBox.shrink();
  }

  /// 操作项
  Widget _buildActionItem(
    IconData icon,
    IconData actionIcon,
    String content,
    bool isSelect, {
    Function()? onTap,
    double? iconSize,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        color: Colors.transparent,
        width: 40,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Icon(
              isSelect ? actionIcon : icon,
              color: isSelect ? theme(context) : disable(context),
              size: iconSize ?? 20,
            ),
            const SizedBox(height: 2),
            Text(
              content,
              style: TextStyle(
                fontSize: 10,
                fontWeight: FontWeight.bold,
                color: black(context).withOpacity(0.7),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
